#! /bin/sh

set -e

PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin
DESC="adbd"
NAME=adb
DAEMON=/opt/android-sdk/platform-tools/$NAME
PIDFILE=/var/run/$NAME.pid
SCRIPTNAME=/etc/init.d/adbd
OPTIONS=""

# Gracefully exit if the package has been removed.
test -x $DAEMON || exit 0

d_start() {
	if [ -f $PIDFILE ]
	then
		PID=`cat $PIDFILE`
		result=`ps ax | grep $PID | grep adb | grep -v grep | awk '{print $1}'` > /dev/null 2>&1
		result=`echo $result | awk '{print $1}'`
		if [ "$result" -eq "$PID" ]
		then
			echo "ADBd status=Already Running"
			exit 0
		fi
	fi
	$DAEMON $OPTIONS || echo " Already Running"
	if [ $? -eq 0 ]
	then
		echo "ADBd status=Running"
	else
		echo "ADBd status=Stopped"
	fi
}

d_status () {
	if [ -f $PIDFILE ]
	then
		PID=`cat $PIDFILE`
		result=`ps ax | grep $PID | grep adb | grep -v grep | awk '{print $1}'` > /dev/null 2>&1
		result=`echo $result | awk '{print $1}'`
		if [ "$result" -eq "$PID" ]
		then
			echo "ADBd status=Running"
			exit 0
		else
			echo "ADBd status=Stopped"
			exit 1
		fi
	else
		echo "ADBd status=Stopped"
		exit 1
	fi
}

d_stop() {
	if [ -f $PIDFILE ]
	then
		PID=`cat $PIDFILE`
		result=`ps ax | grep $PID | grep adb | grep -v grep | awk '{print $1}'` > /dev/null 2>&1
		result=`echo $result | awk '{print $1}'`
		if [ "$result" -eq "$PID" ]
		then
			kill -QUIT $PID
			if [ $? -eq 0 ]; then
				echo "ADBd status=Stopped"
			fi
		else
			rm -f $PIDFILE
			exit 0
		fi
	else
		echo "ADBd status=Stopped"
		exit 0
	fi
}

case "$1" in
  start)
	d_start
	;;
  status)
	d_status
	;;
  stop)
	d_stop
	;;
  restart)
  	echo "Restarting $DESC: $NAME"
  	d_stop
  	sleep 1
  	d_start
	;;
  *)
	  echo "Usage: $SCRIPTNAME {start|status|stop|restart|force-reload}" >&2
	  exit 3
	;;
esac

exit 0
